#!/bin/sh
# perhaps the most unrobust script for one of the most unrobust systems ever, but it does the job, no matter how sloppily

usage="usage: strlst [-s] [-c push|pull|list] [-f file]"

[ $# -lt 2 ] && echo "${usage}" && exit 1

# metadata
port="-P 222"
user="strlst"
webserverfile=${HOME}/.local/share/${USER}/.webserver
webserver=$(cat "${webserverfile}")
url=https://${webserver}/unindexed/
identity="${HOME}/.ssh/copyservice_rsa"
secretfile=${HOME}/.local/share/${USER}/.secret
secret=$(cat "${secretfile}")

[ -z "${webserver}" ] && echo ".webserver not set, cannot transfer" && exit 1
[ -z "${secret}" ] && echo ".secret not set, cannot encrypt" && exit 1

pull () {
    # check for file arg
    [ $# -eq 0 ] && echo "no file specified" && exit 1
    # if save is set, save temp file and exit
    file=/dev/stdout
    [ $# -gt 1 ] && [ "${2}" -eq 1 ] && file="${1}"
    # curl, decode, decrypt and store into target
    curl -s "${url}${1}" | base64 -d | openssl enc -d -aes-256-cbc -k "${secret}" > "${file}"
}

push () {
    [ $# -eq 0 ] && echo "no file specified" && exit 1
    # figure out filename from filepath
    # hint: this entire script burns when dealing with files that have spaces in their names
    file=$(basename "${1}")
    # create temp file for later copying
    tmp=$(mktemp /tmp/strlst.XXXXXXXX) || { echo "failed to create temp file"; exit 1; }
    # encrypt and encode, save intermediary result
    openssl enc -aes-256-cbc -k "${secret}" < "${1}" | base64 > "${tmp}"
    # copy result to webserver
    scp "${port}" -i "${identity}" "${tmp}" "${user}"@"${webserver}":~/dropzone/"${file}"
    # inform user
    echo "pushed ${file}"
    # remove temporary file
    rm -f "${tmp}"
}

list () {
    curl -s "${url}" | grep href | sed -e 's/<[^<]*>//g'
}

target=
command="echo ${usage}"
save=0
IS_C=0
IS_T=0
for arg in "$@"; do

    # check args
    case ${arg} in
        -c|--command)
            IS_C=1
            IS_T=0
            continue
            ;;
        -s|--save)
            save=1
            continue
            ;;
        -f|--file)
            IS_T=1
            IS_C=0
            continue
    esac

    if [ $IS_C -eq 1 ]; then
        command=${arg}
        IS_C=0
    fi

    if [ $IS_T -eq 1 ]; then
        [ ! -f "${arg}" ] && echo "file ${arg} does not exist" && exit 1
        target=${arg}
        IS_T=0
    fi

done

# if no command is set, tell user how to use this thing
[ -z "${command}" ] && echo "${usage}" && exit 1

$command "$target" "$save"
